package com.grape.zookeeper.config;

import org.I0Itec.zkclient.IZkDataListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * 描述:MyApplicationRunner 项目启动运行
 * @author: myx
 * @date: 2019/8/26 0026
 * Copyright © 2019-grape. All rights reserved.
 */
@Component
public class MyApplicationRunner extends BaseZookeeper implements ApplicationRunner {
   @Autowired
   private ConfigUtils configUtils;

    /**
     * 启动后执行方法
    * @param args
     * @throws Exception
    */
   @Override
   public void run(ApplicationArguments args) throws Exception {
      System.out.println("项目启动成功...");
      String myxValue = configUtils.getMyxKey();
      String myxKey = "/myxKey";
      try {
         // 创建节点信息
         zkClient.createEphemeral(myxKey, myxValue);
      } catch (Exception e) {
         e.printStackTrace();
      }
      zkClient.subscribeDataChanges(myxKey, new IZkDataListener() {
         @Override
         public void handleDataDeleted(String dataPath){
         }
         /**
             * 当值发生变化的时候
          * @param dataPath
             * @param data
          */
         @Override
         public void handleDataChange(String dataPath, Object data){
            System.out.println("dataPath:" + dataPath + ",data:" + data);
            final String strData = (String) data;
            configUtils.setMyxKey(strData);
         }
      });

   }

}